package com.xxxx.server.controller;

import com.macro.mall.security.util.CommonResult;
import com.macro.mall.security.util.JwtTokenUtil;
import com.xxxx.server.pojo.AdminLoginParam;
import com.xxxx.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private IAdminService adminService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public CommonResult login(AdminLoginParam adminLoginParam){
        String token = adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword());
        HashMap map = new HashMap<String,String>();
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return CommonResult.success(map);
    }

    @GetMapping("/refresh")
    public CommonResult refresh(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        String refreshHeadToken = jwtTokenUtil.refreshHeadToken(token);
        if (refreshHeadToken == null)
            return CommonResult.failed("token已经过期");
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshHeadToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
    //测试未登录是否被拦截
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}
